package com.example.wordbook;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.LitePal;
import org.litepal.crud.LitePalSupport;
import org.litepal.exceptions.DataSupportException;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    String words[] = {"abandon", "basketball", "cup", "define"};
    String meanings[] = {"抛弃，遗弃", "篮球，篮球运动", "杯子", "定义，界定，明确"};
    List<WordItem> wordItemList = new ArrayList<WordItem>();
    WordItemAdapter_List wordItemAdapter_list = null;
    ListView listView = null;
    EditText editText;

    public void Add_data(){
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        final View input_layout = LayoutInflater.from(MainActivity.this).inflate(R.layout.add_pop, null);
        TextView addWordTV = (TextView) input_layout.findViewById(R.id.add_word);
        TextView addMeaningTV = (TextView) input_layout.findViewById(R.id.add_meaning);
        builder.setTitle("添加新词汇").setIcon(android.R.drawable.ic_dialog_info).setView(input_layout)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String addWord = addWordTV.getText().toString();
                String addMeaning = addMeaningTV.getText().toString();
                WordItem addWordItem = null;
                if(addWord != null)
                    addWordItem = new WordItem(addWord, addMeaning);
                if(addWordItem != null)
                    addWordItem.save();
                wordItemList.add(addWordItem);
                wordItemAdapter_list.notifyDataSetChanged();
            }
        });
        builder.show();
    }

    public void Find_data(){
        Button findButton = (Button)findViewById(R.id.find_data);
        if(findButton.getText().toString().equals("搜词")){
            TextView input = (TextView)findViewById(R.id.input_find);
            String selectWord = input.getText().toString();
            List<WordItem> findList = LitePal.where( "word like ?", selectWord + "%")
                    .find(WordItem.class);
            wordItemList.clear();
            wordItemList.addAll(findList);
            wordItemAdapter_list.notifyDataSetChanged();
            findButton.setText("返回");
        }
        else if(findButton.getText().toString().equals("返回")){
            wordItemList.clear();
            wordItemList.addAll(LitePal.findAll(WordItem.class));
            wordItemAdapter_list.notifyDataSetChanged();
            findButton.setText("搜词");
        }
    }

    public void Delete_data(){
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        final View input_layout = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
        builder.setTitle("确定删除所有词汇？").setIcon(android.R.drawable.ic_dialog_info)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                for(WordItem i:wordItemList)
                    LitePal.deleteAll(WordItem.class, "word = ?", i.getWord());
                wordItemList.clear();
                wordItemAdapter_list.notifyDataSetChanged();
                wordItemAdapter_list.notifyDataSetChanged();
            }
        });
        builder.show();
    }

    @Override
    @SuppressWarnings("ResourceType")
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.add_data:
                Add_data();
                editText.clearFocus();
                break;

            case R.id.delete_data:
                Delete_data();
                editText.clearFocus();
                break;

            case R.id.find_data:
                Find_data();
                editText.clearFocus();
                break;

            case R.id.exit:
                finish();
                break;

            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //隐藏自带标题
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null) actionBar.hide();
        //数据库操作
        Button addData = (Button) findViewById(R.id.add_data);
        addData.setOnClickListener(this);
        Button deleteData = (Button) findViewById(R.id.delete_data);
        deleteData.setOnClickListener(this);
        Button findData = (Button) findViewById(R.id.find_data);
        findData.setOnClickListener(this);
        Button Exit = (Button) findViewById(R.id.exit);
        Exit.setOnClickListener(this);
        //解决按钮被输入法顶上去的问题
        editText = (EditText)findViewById(R.id.input_find);
        final View contentView = LayoutInflater.from(MainActivity.this)
                                    .inflate(R.layout.activity_main, null);
        contentView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                editText.clearFocus();
                return true;
            }
        });
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(editText.hasFocus())
                    Exit.setVisibility(View.GONE);
                else {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    Exit.setVisibility(View.VISIBLE);
                }
            }
        });
        //显示词汇列表
        Connector.getWritableDatabase();
        wordItemList = LitePal.findAll(WordItem.class);
        wordItemAdapter_list = new WordItemAdapter_List
                (MainActivity.this, R.layout.word, wordItemList);
        listView = findViewById(R.id.list_view);
        listView.setAdapter(wordItemAdapter_list);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                editText.clearFocus();
                WordItem wordItem = wordItemList.get(position);
                Toast.makeText(MainActivity.this, wordItem.getWord(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}